package com.scitc.pleasurevideo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.scitc.pleasurevideo.R;
import com.scitc.pleasurevideo.data.HistoryDataMan;

import java.util.List;

public class HistorySearchAdapter extends ArrayAdapter<String> {

    private List<String> items;
    private Context context;

    public HistorySearchAdapter(@NonNull Context context, List<String> items) {
        super(context, 0);
        this.items = items;
        this.context = context;
    }

    public void addAll(List<String> items) {
        if (items == null || items.size() < 1) {
            return;
        }
        this.items.clear();
        this.items.addAll(items);
        notifyDataSetChanged();
    }

    public void addItem(String news) {
        if (news == null || news.trim().length() < 1) {
            return;
        }

        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).equals(news)) {
                return;
            }
        }

        this.items.add(news);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (items == null || items.size() < 1) {
            return 0;
        }
        return items.size();
    }

    @Nullable
    @Override
    public String getItem(int position) {
        if (position < 0 || position >= items.size()) {
            return null;
        }
        return items.get(position);
    }

    class ViewHolder {

        TextView title;
        ImageView igDelete;

    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        final String news = items.get(position);

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        convertView = layoutInflater.inflate(R.layout.item_search_history, parent, false);
        ViewHolder holder = new ViewHolder();
        holder.title = (TextView) convertView.findViewById(R.id.title);
        holder.igDelete = (ImageView) convertView.findViewById(R.id.ig_delete);
        if (holder.title != null) {
            holder.title.setText(news);
        }
        if (holder.igDelete != null) {
            holder.igDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    items.remove(position);
                    HistoryDataMan.getHistoryDataMan().clearHistoryQueryString(context, news);
                    notifyDataSetChanged();
                }
            });
        }

        return convertView;
    }
}
